package com.lolong.main;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Path;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lolong.controller.ShowRoads;
import com.lolong.model.Points;
import com.lolong.model.Roads;

public class MapsActivity extends MapActivity{
    /** Called when the activity is first created. */
	
	MapView map=null;
	MapController mc=null;
	GeoPoint gpt=null,p=null, q=null;
	LinearLayout linlay;
	private Roads mRoads;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.maps);
        
        map = (MapView)findViewById(R.id.mvMapsActivity);
        map.setBuiltInZoomControls(true);
        map.setSatellite(false);
        mc = map.getController();
        
        final double srclat = 14.556056;
        final double srclong = 121.021625;
        double destlat = 14.558143;
        double destlong= 121.013128;
        
        gpt = new GeoPoint((int) (srclat*1e6), (int) (srclong*1e6));
        q = new GeoPoint((int)(destlat*1e6), (int) (destlong*1e6));
        
        new Thread() {
           
            public Location getCoords(){
        		Intent i = getIntent();
        		String endLoc = i.getExtras().getString("address");

        		Location endLocs = new Location ("End Loc");
        		Geocoder gCoder = new Geocoder (getBaseContext(), Locale.getDefault());
        		try{
        			List<Address> addrs =gCoder.getFromLocationName(endLoc, 2);
        			while(addrs.size()==0){ addrs = gCoder.getFromLocationName(endLoc, 2);}
        			
        			if(addrs.size()>0){
        				Address addr = addrs.get(0);
        				endLocs.setLatitude(addr.getLatitude());
        				endLocs.setLongitude(addr.getLongitude());
        			}
        		}catch(Exception e){System.out.print(e.getMessage());}
        		
        		return endLocs;
        	}
            @Override
            public void run() {
                    double toLat = getCoords().getLatitude(), toLon = getCoords().getLongitude();
                    String url = ShowRoads.getUrl(srclat, srclong, toLat, toLon);
                    
                    InputStream is = getConnection(url);
                    mRoads = ShowRoads.getRoute(is);
                    mHandler.sendEmptyMessage(0);
            }
    }.start();
        
        LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        LocationListener mlocListener = new MyLocListener();
        mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
        
    }
	
	Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
                TextView textView = (TextView) findViewById(R.id.description);
                textView.setText(mRoads.rName + " " + mRoads.rDesc);
                mapOverlay mOlay = new mapOverlay(mRoads, map);
                List<Overlay> olayList = map.getOverlays();
                olayList.clear();
                olayList.add(mOlay);
                map.invalidate();
        };
	};


	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	
	
	class mapOverlay extends Overlay{
			 Roads mRoads;
			 ArrayList<GeoPoint> gPoints;
			 
			public mapOverlay(Roads nRoads, MapView mv){
				mRoads = nRoads;
				
				if (nRoads.rRoute.length > 0) {
                    gPoints = new ArrayList<GeoPoint>();
                    
                    for (int i = 0; i < nRoads.rRoute.length; i++) {
                            gPoints.add(new GeoPoint((int) (nRoads.rRoute[i][1] * 1000000),
                                            (int) (nRoads.rRoute[i][0] * 1000000)));
                    }
                
                    int moveToLat = (gPoints.get(0).getLatitudeE6() + (gPoints.get(
                                    gPoints.size() - 1).getLatitudeE6() - gPoints.get(0)
                                    .getLatitudeE6()) / 2);
                    
                    int moveToLong = (gPoints.get(0).getLongitudeE6() + (gPoints.get(
                                    gPoints.size() - 1).getLongitudeE6() - gPoints.get(0)
                                    .getLongitudeE6()) / 2);
                    
                    GeoPoint moveTo = new GeoPoint(moveToLat, moveToLong);

                    mc = mv.getController();
                    mc.animateTo(moveTo);
                    mc.setZoom(17);
				}
			}
			
		@Override	
		 public boolean draw(Canvas canvas, MapView mv, boolean shadow, long when) {
	             super.draw(canvas, mv, shadow);
	             Point scrnPts = new Point();
					mv.getProjection().toPixels(gpt, scrnPts);
		
					Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.marker1);
					canvas.drawBitmap(bmp,scrnPts.x-10,scrnPts.y-65, null);
					
					if(q!=null){
					Point scrnPts2 = new Point();
					mv.getProjection().toPixels(q,scrnPts2);
					canvas.drawBitmap(bmp, scrnPts2.x-10, scrnPts2.y-45, null);
					}
	             drawPath(mv, canvas);
	             return true;
	     }

	     public void drawPath(MapView mv, Canvas canvas) {
	    	 
	             int x1 = -1, y1 = -1, x2 = -1, y2 = -1;
	             Paint paint = new Paint();
	             paint.setColor(Color.GREEN);
	             paint.setStyle(Paint.Style.FILL_AND_STROKE);
	             paint.setStrokeWidth(5);
	         
	             for (int i = 0; i < gPoints.size(); i++) {
	                     Point point = new Point();
	                     mv.getProjection().toPixels(gPoints.get(i), point);
	                     x2 = point.x;
	                     y2 = point.y;
	                     if (i > 0) {
	                             canvas.drawLine(x1, y1, x2, y2, paint);
	                     }
	                     x1 = x2;
	                     y1 = y2;
	             }
	     }
	}
			
	 private InputStream getConnection(String url) {
         InputStream istream = null;
         try {
                 URLConnection conn = new URL(url).openConnection();
                 istream = conn.getInputStream();
         } catch (MalformedURLException e) {
                 e.printStackTrace();
         } catch (IOException e) {
                 e.printStackTrace();
         }
         return istream;
 }

	
	
	//public passDistance(){
	/*Intent i = new Intent(this, classNameHere.class);
	 * int distToPass = distance here;
	 * 
	 * Bundle bdle = new Bundle();
	 * bundle.putInt("distance", distToPass);
	 * i.putExtras(bdle);
	 * 
	 * startActivity(i);
	 * }*/
	 
	public class MyLocListener implements LocationListener{
		@Override
		public void onLocationChanged(Location loc) {
			// TODO Auto-generated method stub
			double lat=loc.getLatitude();
			double longi=loc.getLongitude();
		
			gpt = new GeoPoint((int)(lat*1e6), (int)(longi*1e6));
			
			mc.animateTo(gpt);
			mc.setZoom(15);
			map.invalidate();			

		}

		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
			Toast.makeText( getApplicationContext(),
							"Gps Disabled",
							Toast.LENGTH_SHORT ).show();
			
		}

		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
			Toast.makeText( getApplicationContext(),
					"Gps Enabled",
					Toast.LENGTH_SHORT ).show();

		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
			
		}
	}
}
